<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\validate;

use DateTime;
use Exception;

class IDValidator
{
    private static $instance = null;

    public static function instance()
    {
        if (self::$instance === null) {
            self::$instance = new \Jxlwqq\IdValidator\IdValidator();
        }

        return self::$instance;
    }

    /**
     * 获取性别
     *
     * @param $idno
     * @return int
     */
    public static function gender($idno)
    {
        $info = self::instance()->getInfo($idno);
        if (!$info) {
            return 0;
        }

        return $info['sex'] == 0 ? 1 : 2;
    }

    /**
     * 获取生日
     *
     * @param $idno
     * @return mixed
     */
    public static function birthday($idno)
    {
        $info = self::instance()->getInfo($idno);
        return $info['birthdayCode'];
    }

    /**
     * @param $idno
     * @return int
     * @throws Exception
     */
    public static function age($idno)
    {
        if (self::instance()->isValid($idno) === false) {
            return 0;
        }

        $info = self::instance()->getInfo($idno);
        $birthday = $info['birthdayCode'];

        // 创建 DateTime 对象
        $birthDate = new DateTime($birthday);
        $currentDate = new DateTime();

        // 计算年龄
        $ageInterval = $currentDate->diff($birthDate);
        return $ageInterval->y;
    }
}
